package main

import (
	"fmt"
	"io"
	"os"
)

/*
这是一个defer关闭文件资源的例子代码
*/
func main() {
	err := do()
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("main正常结束")
	}
}

func do() error {
	f, err := os.Open("D:\\Programs\\Projects\\Go\\220315_GoSelfLearn\\17GoError\\files\\book.txt")
	if err != nil {
		return err
	}
	if f != nil {
		defer func(f io.Closer) {
			fmt.Println("开始准备关闭book.txt资源。。")
			if err := f.Close(); err != nil {
				fmt.Printf("defer close book.txt err %v\n", err)
			}
		}(f)
	}

	// ..code...

	f, err = os.Open("D:\\Programs\\Projects\\Go\\220315_GoSelfLearn\\17GoError\\files\\another-book.txt")
	if err != nil {
		return err
	}
	if f != nil {
		defer func(f io.Closer) {
			fmt.Println("开始准备关闭another-book.txt资源。。")
			if err := f.Close(); err != nil {
				fmt.Printf("defer close another-book.txt err %v\n", err)
			}
		}(f)
	}

	return nil
}
